What is string-width?
The string-width npm package is used to calculate and return the visual width of a string - the number of columns required to display it. This is particularly useful when dealing with strings containing characters that may take up more than one column in terminals or monospaced fonts, such as emojis or certain international characters.
What are string-width's main functionalities?
Calculate string width
This feature calculates the visual width of a string. For example, an ASCII character has a width of 1, while many CJK characters have a width of 2. Emojis can also have a width of 2 or more.
const stringWidth = require('string-width');
console.log(stringWidth('古')); // 2
console.log(stringWidth('a')); // 1
console.log(stringWidth('👍')); // 2
Other packages similar to string-width
wcwidth
The wcwidth package is similar to string-width in that it provides functionality to determine the number of terminal column cells a wide-character string will occupy. It is based on the wcwidth() function defined in POSIX.1-2001 and POSIX.1-2008 which is used in Unix-based systems.
eastasianwidth
This package is designed to provide the functionality to determine the East Asian Width property as defined by Unicode. It can be used to figure out if a character is full-width, half-width, wide, narrow, ambiguous, or neutral. This is similar to string-width but focuses specifically on East Asian characters.
string-pixel-width
While string-width calculates the number of columns a string will take up in a monospaced font, string-pixel-width calculates the width of a string in pixels. This is useful for determining the actual rendered width of a string in a web page or an application with proportional fonts.
string-width
Get the visual width of a string - the number of columns required to display it
Some Unicode characters are fullwidth and use double the normal width. ANSI escape codes are stripped and doesn't affect the width.
Useful to be able to measure the actual width of command-line output.
Install
npm install string-width
Usage
import stringWidth from 'string-width';
stringWidth('a');
stringWidth('古');
stringWidth('\u001B[1m古\u001B[22m');
API
stringWidth(string, options?)
string
Type: string
The string to be counted.
options
Type: object
ambiguousIsNarrow
Type: boolean
Default: true
Count ambiguous width characters as having narrow width (count of 1) instead of wide width (count of 2).
Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). If the context cannot be established reliably, they should be treated as narrow characters by default.
countAnsiEscapeCodes
Type: boolean
Default: false
Whether ANSI escape codes should be counted.
Related